package com.larry.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ProjectName JUC
 * @Author larry
 * @Date 11:31 2021/7/16
 * @Description 自旋锁
 **/
public class SpinLockDemo {

    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock(){
        System.out.println(Thread.currentThread().getName() + " 进入持有锁");
        while (!atomicReference.compareAndSet(null,Thread.currentThread())){

        }
        System.out.println(Thread.currentThread().getName() + " 持有锁成功");
    }

    public void myUnLock(){
        atomicReference.compareAndSet(Thread.currentThread(),null);
        System.out.println(Thread.currentThread().getName() + " 释放锁成功");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.myLock();
            try { TimeUnit.SECONDS.sleep(5); }catch (InterruptedException e){ e.printStackTrace(); }
            spinLockDemo.myUnLock();
        },"a").start();

        new Thread(() -> {
               spinLockDemo.myLock();
               spinLockDemo.myUnLock();
        },"b").start();
    }

}
